from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)


class Todo(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String)
    description = db.Column(db.String)
    create_time = db.Column(db.DateTime)
    due_time = db.Column(db.DateTime)
    is_completed = db.Column(db.Boolean)

    def to_json(self):
        return {c.name: getattr(self, c.name) for c in self.__table__.columns}


@app.route('/all')
def query_all():
    todo_list = Todo.query.order_by(Todo.due_time).all()
    return jsonify([todo.to_json() for todo in todo_list])


@app.route('/add', methods=['POST'])
def add():
    title = request.form.get('title')
    description = request.form.get('description')
    create_time = datetime.now()
    due_time = request.form.get('due_time')
    year, month, day = due_time.split('-')
    due_time = datetime(int(year), int(month), int(day))
    new_todo = Todo(title=title,
                    description=description,
                    create_time=create_time,
                    due_time=due_time,
                    is_completed=False)
    db.session.add(new_todo)
    db.session.commit()
    return new_todo.to_json()


@app.route('/check', methods=['POST'])
def check():
    id = request.form.get('id')
    todo = Todo.query.filter_by(id=id).first()
    if todo:
        todo.is_completed = not todo.is_completed
        db.session.commit()
        return todo.to_json()
    else:
        return f"id '{id}' is invalid.\n"


@app.route('/update', methods=['POST'])
def update():
    id = request.form.get('id')
    todo = Todo.query.filter_by(id=id).first()
    if todo:
        title = request.form.get('title')
        if title:
            todo.title = title
        description = request.form.get('description')
        if description:
            todo.description = description
        due_time = request.form.get('due_time')
        if due_time:
            year, month, day = due_time.split('-')
            due_time = datetime(int(year), int(month), int(day))
            todo.due_time = due_time
        db.session.commit()
        return todo.to_json()
    else:
        return f"id '{id}' is invalid.\n"

@app.route('/delete', methods=['POST'])
def delete():
    id = request.form.get('id')
    todo = Todo.query.filter_by(id=id).first()
    db.session.delete(todo)
    db.session.commit()
    return todo.to_json()


if __name__ == "__main__":
    with app.app_context():
        db.create_all()
        app.run(debug=True)
